import React, { useRef, useEffect, useState } from 'react';
import { Typography, Card, Row, Col, Table, Tag, Progress } from 'antd';
import ReactECharts from 'echarts-for-react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

const { Title } = Typography;

interface RiskData {
  riskEnterprises: {
    key: string;
    name: string;
    riskLevel: string;
    riskReason: string;
  }[];
  riskLevels: {
    value: number;
    name: string;
  }[];
}

const RiskPage: React.FC = () => {
  const navigate = useNavigate();

  const [tableData, setTableData] = useState<RiskData['riskEnterprises']>([]);
  const [loading, setLoading] = useState(true);
  const [riskChartOptions, setRiskChartOptions] = useState({
    title: { text: '风险等级分布', left: 'center', textStyle: { fontSize: 18, color: '#333' } },
    tooltip: { trigger: 'item' },
    legend: { bottom: '0', textStyle: { color: '#333' } },
    series: [
      {
        name: '风险等级',
        type: 'pie',
        radius: ['40%', '70%'],
        data: [] as { value: number; name: string }[],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  });

  const [riskStats, setRiskStats] = useState({
    high: 0,
    medium: 0,
    low: 0,
  });

  const columns = [
    {
      title: '企业名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: RiskData['riskEnterprises'][number]) => (
        <a
          onClick={() => navigate(`/enterprise/${record.name}`)}
          style={{ color: '#1890ff', cursor: 'pointer', fontWeight: 'bold' }}
        >
          {text}
        </a>
      ),
    },
    {
      title: '风险等级',
      dataIndex: 'riskLevel',
      key: 'riskLevel',
      render: (text: string) => (
        <Tag color={text === '高' ? 'red' : text === '中' ? 'orange' : 'green'}>{text}</Tag>
      ),
    },
    {
      title: '风险评分',
      dataIndex: 'riskReason',
      key: 'riskReason',
    },
  ];

  const tableContainerRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const container = tableContainerRef.current;
    if (!container) return;
    let scrollInterval: NodeJS.Timeout;
    const startScrolling = () => {
      scrollInterval = setInterval(() => {
        container.scrollTop += 1;
        if (container.scrollTop + container.clientHeight >= container.scrollHeight) {
          container.scrollTop = 0;
        }
      }, 50);
    };
    startScrolling();
    return () => {
      clearInterval(scrollInterval);
    };
  }, []);

  useEffect(() => {
    axios
      .get<RiskData>('http://localhost:5000/api/risk')
      .then((response) => {
        const { riskEnterprises, riskLevels } = response.data;
        setTableData(riskEnterprises);
        setRiskChartOptions((prev) => ({
          ...prev,
          series: [{ ...prev.series[0], data: riskLevels }],
        }));
        const total = riskLevels.reduce((sum, level) => sum + level.value, 0);
        const high = riskLevels.find((level) => level.name === '高')?.value || 0;
        const medium = riskLevels.find((level) => level.name === '中')?.value || 0;
        const low = riskLevels.find((level) => level.name === '低')?.value || 0;

        setRiskStats({
          high: Math.round((high / total) * 100),
          medium: Math.round((medium / total) * 100),
          low: Math.round((low / total) * 100),
        });
        setLoading(false);
      })
      .catch((error) => {
        console.error('Error fetching risk data:', error);
        setLoading(false);
      });
  }, []);

  const rankingData = [...tableData]
    .sort((a, b) => {
      const scoreA = parseFloat(a.riskReason) || 0;
      const scoreB = parseFloat(b.riskReason) || 0;
      return scoreB - scoreA;
    })
    .slice(0, 10);

  const rankingColumns = [
    {
      title: '排名',
      key: 'rank',
      render: (_: unknown, _record: RiskData['riskEnterprises'][number], index: number) => index + 1,
    },
    {
      title: '企业名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: RiskData['riskEnterprises'][number]) => (
        <a
          onClick={() => navigate(`/enterprise/${record.name}`)}
          style={{ color: '#1890ff', cursor: 'pointer', fontWeight: 'bold' }}
        >
          {text}
        </a>
      ),
    },
    {
      title: '风险评分',
      dataIndex: 'riskReason',
      key: 'riskReason',
      render: (text: string) => <Tag color="purple">{text}</Tag>,
    },
  ];

  return (
    <div
      style={{
        padding: '20px',
        background: 'linear-gradient(to bottom, #e1f7fe, #ffffff)', // 背景渐变
        minHeight: '100vh',
        fontFamily: 'Arial, sans-serif',
      }}
    >
      <Title
        level={2}
        style={{
          textAlign: 'center',
          marginBottom: '20px',
          color: '#333',
          fontWeight: 'bold',
          textShadow: '1px 1px 2px rgba(0, 0, 0, 0.2)',
        }}
      >
        风险企业详情
      </Title>

      <Row gutter={[16, 16]} style={{ marginBottom: '20px' }}>
        <Col span={8}>
          <Card
            title="高风险企业"
            bordered={false}
            style={{
              borderRadius: '12px',
              boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
              background: 'linear-gradient(to bottom, #ffd5d5, #ffffff)',
            }}
          >
            <Progress
              type="circle"
              percent={riskStats.high}
              format={(percent) => `${percent}%`}
              status="exception"
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card
            title="中风险企业"
            bordered={false}
            style={{
              borderRadius: '12px',
              boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
              background: 'linear-gradient(to bottom, #fff8b3, #ffffff)',
            }}
          >
            <Progress
              type="circle"
              percent={riskStats.medium}
              format={(percent) => `${percent}%`}
              status="normal"
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card
            title="低风险企业"
            bordered={false}
            style={{
              borderRadius: '12px',
              boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
              background: 'linear-gradient(to bottom, #d9f7be, #ffffff)',
            }}
          >
            <Progress
              type="circle"
              percent={riskStats.low}
              format={(percent) => `${percent}%`}
              status="success"
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginBottom: '20px' }}>
        <Col span={24}>
          <Card
            title="风险率排行榜（前 10 名）"
            bordered={false}
            style={{
              borderRadius: '12px',
              boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
              background: '#ffffff',
            }}
          >
            <Table
              dataSource={rankingData}
              columns={rankingColumns}
              pagination={false}
              loading={loading}
              size="small"
              rowKey="name"
              bordered
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col span={12}>
          <Card
            title="风险企业列表"
            bordered={false}
            style={{
              borderRadius: '12px',
              boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
              background: '#ffffff',
            }}
          >
            <div
              ref={tableContainerRef}
              style={{
                maxHeight: '240px',
                overflow: 'hidden',
                position: 'relative',
              }}
            >
              <Table
                dataSource={tableData}
                columns={columns}
                pagination={false}
                scroll={{ y: 240 }}
                loading={loading}
                style={{ marginTop: '10px' }}
                rowKey="name"
              />
            </div>
          </Card>
        </Col>
        <Col span={12}>
          <Card
            title="风险等级分布"
            bordered={false}
            style={{
              borderRadius: '12px',
              boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
              background: '#ffffff',
            }}
          >
            <ReactECharts option={riskChartOptions} style={{ height: '300px' }} />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default RiskPage;
